<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Post Viewer</title>
    <link rel="stylesheet" href="/static/postinfo.css">
    <script src="https://cdn.jsdelivr.net/npm/jwt-decode@3.1.2/build/jwt-decode.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/dompurify/2.3.11/purify.min.js"></script>
</head>
<body>
<div id="post-container">
    <h1 id="post-title"></h1>
    <p>帖主: <span id="post-author"></span></p>
    <div id="post-content">
        <p id="post-content-text"></p>
        <img id="post-img">
        <div id="interaction-counts">
            <button onclick="increaseLike()">点赞: <span id="post-likes">0</span></button>
            <button onclick="increasecollect()">收藏: <span id="post-collects">0</span></button>
        </div>
    </div>
    <div id="comments-container">
        <h2>评论区</h2>
        <!-- 假设评论加载在这里 -->
    </div>
    <div id="comment-form-container">
        <h3>发表评论</h3>
        <form id="comment-form">
            <textarea id="comment-content" name="content" placeholder="输入你的评论..." required></textarea>
            <button type="submit">提交评论</button>
        </form>
    </div>
</div>

<script>
    function increaseLike() {
        const token = localStorage.getItem('token'); // 从 localStorage 中获取 token
        if (!token) {
            if (confirm("未登录，请先登录！是否跳转到登录页面？")) {
                window.location.href = '/login'; // 跳转到登录页面
            }
            return;
        }
        console.log("从本地拿到的token是",token)
        const postId = window.location.search.split('=')[1];
        fetch(`/api/v1/post/searchpid/like?id=${postId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Token': token
            },
        }) // 假设使用POST请求
            .then(response => response.json())
            .then(data => {
                if (data.code === 0) {
                    document.getElementById('post-likes').textContent = data.data.likecount;
                    // window.location.href = `/api/v1/post/searchpidHTML?id=${postId}`;
                } else {
                    alert('点赞失败');
                }
            })
            .catch(error => console.error('Error:', error));
    }

    function increasecollect() {
        const token = localStorage.getItem('token'); // 从 localStorage 中获取 token
        if (!token) {
            if (confirm("未登录，请先登录！是否跳转到登录页面？")) {
                window.location.href = '/login'; // 跳转到登录页面
            }
            return;
        }
        console.log("从本地拿到的token是",token)
        const postId = window.location.search.split('=')[1];
        fetch(`/api/v1/post/searchpid/collect?id=${postId}`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Token': token
            },
        }) // 假设使用POST请求
            .then(response => response.json())
            .then(data => {
                if (data.code === 0) {
                    document.getElementById('post-likes').textContent = data.data.likecount;
                    document.getElementById('post-collects').textContent = data.data.collectcount;
                } else {
                    alert('收藏失败');
                }
            })
            .catch(error => console.error('Error:', error));
    }

    document.addEventListener('DOMContentLoaded', function() {
        const postId = window.location.search.split('=')[1];

        // 初始加载帖子详情
        fetch(`/api/v1/post/searchpid?id=${postId}`) // 假设URL已更改以返回完整帖子详情
            .then(response => response.json())
            .then(data => {
                if (data.code === 0) {
                    const post = data.data;
                    fetchAuthorName(post.pid) // 假设使用uid来获取作者名
                        .then(authorName => {
                            updatePostDetails(post, authorName);
                            fetchComments(post.pid);
                        })
                        .catch(error => {
                            console.error('Error fetching author name:', error);
                            document.getElementById('post-author').textContent = 'Unknown Author';
                        });
                } else {
                    alert('帖子数据加载失败');
                }
            })
            .catch(error => {
                console.error('Error fetching post data:', error);
                alert('帖子数据加载失败');
            });
        document.getElementById('comment-form').addEventListener('submit', function(event) {
            event.preventDefault(); // 阻止表单默认提交行为

            const content = document.getElementById('comment-content').value;
            const postId = window.location.search.split('=')[1];
            const postIdint = parseInt(postId, 10);
            const token = localStorage.getItem('token'); // 从 localStorage 中获取 token

            if (!content.trim()) {
                alert('评论内容不能为空');
                return;
            }

            // 解析 token 获取 uid
            let userId = 1; // 默认值
            try {
                const decodedToken = jwt_decode(token);
                userId = decodedToken.uid; // 假设 token 中的 uid 字段名为 uid
            } catch (error) {
                console.error('Error decoding token:', error);
                alert('无法解析token');
                return;
            }

            fetch(`/post/addcomment?id=${postId}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Token': token
                },
                body: JSON.stringify({
                    uid: userId,
                    content: content,
                    pid: postIdint
                })
            })
                .then(response => response.json())
                .then(data => {
                    console.log("POST的返回信息",data)
                    if (data.code === 0 && data.data) {
                        alert('评论成功');
                        document.getElementById('comment-content').value = ''; // 清空输入框
                        fetchComments(postId); // 重新加载评论
                    } else {
                        alert('评论失败: ' + data.msg);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('评论失败');
                });
        });

        // 辅助函数
        function updatePostDetails(post, authorName) {
            document.getElementById('post-title').textContent = post.title;
            document.getElementById('post-img').src = post.imageurl;
            document.getElementById('post-author').textContent = authorName;
            // 使用 DOMPurify 净化并显示有格式的内容
            const cleanContent = DOMPurify.sanitize(post.content);
            document.getElementById('post-content-text').innerHTML = cleanContent;
            document.getElementById('post-likes').textContent = post.likecount;
            document.getElementById('post-collects').textContent = post.collectcount;
        }

        // 定义一个函数来根据pid获取作者姓名
        function fetchAuthorName(pid) {
            return fetch(`/post/writer?id=${pid}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => {
                    // 假设返回的data对象中有一个name属性是作者的姓名
                    console.log(data.data)
                    return data.data.username; // 或者其他表示姓名的属性
                });
        }


        // 定义一个函数来加载评论
        function fetchComments(pid) {
            fetch(`/post/comment?id=${pid}`) // 假设的URL
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.error) {
                        alert(data.error);
                        return;
                    }

                    const commentsContainer = document.getElementById('comments-container');
                    commentsContainer.innerHTML = ''; // 清空之前的评论

                    data.data.forEach(comment => {
                        fetchUserName(comment.cid)
                            .then(userName => {
                                console.log(comment)
                                const commentElement = document.createElement('div');
                                // 同样使用 DOMPurify 净化评论内容
                                const cleanComment = DOMPurify.sanitize(comment.content);
                                commentElement.innerHTML = `${userName}: ${cleanComment}`;
                                commentsContainer.appendChild(commentElement);
                            })
                            .catch(error => {
                                console.error('Error fetching user name for comment:', error);
                            });
                    });
                })
                .catch(error => {
                    console.error('Error fetching comments:', error);
                    alert('Failed to load comments.');
                });
        }
        // 定义一个函数来根据cid获取作者姓名
        function fetchUserName(cid) {
            return fetch(`/comment/user?id=${cid}`) // 假设的URL
                .then(response => {
                    if (!response.ok) {
                        throw new Error('Network response was not ok');
                    }
                    return response.json();
                })
                .then(data => data.data.username); // 假设返回的JSON对象直接包含username属性

        }
    });
</script>
</body>
</html>